package com.maltys.greedy;

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Map;

public class MergeIntervals {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));
        int start = intervals[0][0];
        int end = intervals[0][1];
        LinkedList<int[]> queue = new LinkedList<>();
        for (int[] interval : intervals) {
            if (interval[0] <= end) {
                end = Math.max(interval[1], end);
            } else {
                queue.add(new int[]{start, end});
                start = interval[0];
                end = interval[1];
            }
        }
        queue.add(new int[]{start, end});

        return queue.toArray(new int[queue.size()][]);
    }

    public static void main(String[] args) {
        MergeIntervals intervals = new MergeIntervals();
        int[][] merge = intervals.merge(new int[][]{{1, 4}, {4, 5}});
        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
    }
}
